import { useLocation } from "react-router";
import { useProject } from "../../hooks/useProjects";
import { useTask, useTasks } from "../../hooks/useTasks";
import { useBillboards } from "../../hooks/useBillboards";
import { useUrlQueryParam } from "../../hooks/useUrlQueryParam";
import { useMemo } from "react";

export const useProjectIdInUrl = () => {
  const { pathname } = useLocation();
  const id = pathname.match(/projects\/(\d+)/)?.[1];
  return Number(id);
};

export const useProjectInUrl = () => useProject(useProjectIdInUrl());
export const useBillboardSearchParam = () => {
  const projectId = useProjectIdInUrl();
  return useMemo(() => ({ projectId }), [projectId]);
};

export const useBillboardsInProject = () =>
  useBillboards(useBillboardSearchParam());

export const useTasksSearchParams = () => {
  const projectId = useProjectIdInUrl();
  const [searchParams] = useUrlQueryParam([
    "name",
    "typeId",
    "tagId",
    "processorId",
  ]);
  return useMemo(
    () => ({
      projectId,
      typeId: Number(searchParams.typeId) || undefined,
      processorId: Number(searchParams.processorId) || undefined,
      tagId: Number(searchParams.tagId) || undefined,
      name: searchParams.name || undefined,
    }),
    [projectId, searchParams]
  );
};

export const useSearchTasks = () => useTasks(useTasksSearchParams());

export const useTasksQueryKey = () => ["tasks", useTasksSearchParams()];

export const useTaskQueryKey = () => {
  const [{ editingTaskId }] = useUrlQueryParam(["editingTaskId"]);
  return ["tasks", editingTaskId, useTasksSearchParams()];
};

export const useBillboardQueryKey = () => [
  "kanbans",
  useBillboardSearchParam(),
];

export const useTaskModal = () => {
  const [{ editingTaskId }, setEditingTaskId] = useUrlQueryParam([
    "editingTaskId",
  ]);
  const { data: taskToBeEdited, isLoading } = useTask(Number(editingTaskId));
  const openTaskModal = (id: number) => {
    setEditingTaskId({ editingTaskId: id });
  };
  const closeTaskModal = () => {
    setEditingTaskId({ editingTaskId: "" });
  };
  return {
    taskModalVisible: Boolean(editingTaskId),
    taskToBeEdited,
    isLoading,
    openTaskModal,
    closeTaskModal,
  };
};
